package com.feeling.oafeeling.utils.util.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.feeling.oafeeling.pojo.SysUser;
import org.springframework.stereotype.Component;

import java.util.Calendar;

@Component
public class TokenService {

//

    //token秘钥
    public static final String TOKEN_SECRET = "SmTicket";

    public String getToken(SysUser user) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,1);
//        Map<String,SysUser> map= new HashMap<String,SysUser>();
//        map.put("user",user);
//        LinkedList<SysUser> list = new LinkedList<>();
//        list.add(user);
        String token="";
        token= JWT.create().withAudience(String.valueOf(user.getUserId()))
                .withIssuer("auth0")
                .withClaim("userName",user.getUserName())
                .withClaim("userId",user.getUserId())
                .sign(Algorithm.HMAC256(TOKEN_SECRET));
        return token;
    }

    public Long verifyToken(String token){
        Long value=null;
        // 使用了HMAC256加密算法。
        // Token_secret是用来加密数字签名的密钥。
        DecodedJWT jwt = null;
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();// Reusable
        // verifier
        // instance
        jwt = verifier.verify(token);
        value= jwt.getClaim("userId").asLong();
        return value;

    }

    public String verifyTokenForName(String token){
        String value=null;
        // 使用了HMAC256加密算法。
        // Token_secret是用来加密数字签名的密钥。
        DecodedJWT jwt = null;
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();// Reusable
        // verifier
        // instance
        jwt = verifier.verify(token);
        value= jwt.getClaim("userName").asString();
        return value;
    }
}
